package com.sddnytsh.body_buildingsystem.screens

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.Profile
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.json.JSONObject

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(navController: NavController) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFF667EEA),
                        Color(0xFF764BA2)
                    )
                )
            )
    ) {
        // 背景装饰
        Image(
            painter = painterResource(id = R.drawable.bg_pattern),
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop,
            alpha = 0.1f
        )

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            // 应用Logo和标题
            Image(
                painter = painterResource(id = R.drawable.ic_fitness),
                contentDescription = "App Logo",
                modifier = Modifier.size(120.dp)
            )

            Spacer(modifier = Modifier.height(24.dp))

            Text(
                text = "健身伴侣",
                style = MaterialTheme.typography.headlineLarge.copy(
                    color = Color.White,
                    fontWeight = FontWeight.Bold,
                    fontSize = 32.sp
                )
            )

            Text(
                text = "开启您的健康之旅",
                style = MaterialTheme.typography.bodyLarge.copy(
                    color = Color.White.copy(alpha = 0.8f),
                    fontSize = 16.sp
                ),
                modifier = Modifier.padding(top = 8.dp)
            )

            Spacer(modifier = Modifier.height(40.dp))

            // 登录表单
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color.White.copy(alpha = 0.95f))
                    .padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                OutlinedTextField(
                    value = username,
                    onValueChange = { username = it },
                    label = {
                        Text(
                            "用户名/邮箱",
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                        )
                    },
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Person,
                            contentDescription = "用户名",
                            tint = MaterialTheme.colorScheme.primary
                        )
                    },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color.Transparent,
                        unfocusedContainerColor = Color.Transparent,
                        focusedTextColor = MaterialTheme.colorScheme.onSurface,
                        unfocusedTextColor = MaterialTheme.colorScheme.onSurface,
                        focusedIndicatorColor = MaterialTheme.colorScheme.primary,
                        unfocusedIndicatorColor = Color.Gray.copy(alpha = 0.4f),
                        cursorColor = MaterialTheme.colorScheme.primary,
                        focusedLabelColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f),
                        unfocusedLabelColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                    ),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                    singleLine = true
                )

                Spacer(modifier = Modifier.height(16.dp))

                OutlinedTextField(
                    value = password,
                    onValueChange = { password = it },
                    label = {
                        Text(
                            "密码",
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                        )
                    },
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Lock,
                            contentDescription = "密码",
                            tint = MaterialTheme.colorScheme.primary
                        )
                    },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color.Transparent,
                        unfocusedContainerColor = Color.Transparent,
                        focusedTextColor = MaterialTheme.colorScheme.onSurface,
                        unfocusedTextColor = MaterialTheme.colorScheme.onSurface,
                        focusedIndicatorColor = MaterialTheme.colorScheme.primary,
                        unfocusedIndicatorColor = Color.Gray.copy(alpha = 0.4f),
                        cursorColor = MaterialTheme.colorScheme.primary,
                        focusedLabelColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f),
                        unfocusedLabelColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                    ),
                    visualTransformation = PasswordVisualTransformation(),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                    singleLine = true
                )

                if (errorMessage.isNotEmpty()) {
                    Text(
                        text = errorMessage,
                        color = MaterialTheme.colorScheme.error,
                        modifier = Modifier
                            .padding(top = 16.dp)
                            .fillMaxWidth(),
                        textAlign = TextAlign.Center
                    )
                }

                Spacer(modifier = Modifier.height(24.dp))

                Button(
                    onClick = {
                        if (username.isNotBlank() && password.isNotBlank()) {
                            isLoading = true
                            errorMessage = ""
                            Login(
                                username, password,
                                onSuccess = { user ->
                                    isLoading = false
                                    UserState.currentUser = user
                                    
                                    // 🔥 登录成功后初始化用户头像
                                    initializeUserAvatarAfterLogin(user.id)
                                    
                                    navController.navigate("main")
                                },
                                onError = { message ->
                                    isLoading = false
                                    errorMessage = message
                                }
                            )
                        } else {
                            errorMessage = "用户名和密码不能为空"
                        }
                    },
                    enabled = !isLoading,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.dp),
                    shape = RoundedCornerShape(12.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = Color.White
                    )
                ) {
                    if (isLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            strokeWidth = 2.dp,
                            color = Color.White
                        )
                    } else {
                        Text(
                            text = "登录",
                            style = TextStyle(
                                fontWeight = FontWeight.Bold,
                                fontSize = 16.sp
                            )
                        )
                    }
                }

                Spacer(modifier = Modifier.height(16.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "还没有账号？",
                        color = Color.Gray,
                        fontSize = 14.sp
                    )

                    TextButton(
                        onClick = { navController.navigate("register") },
                        enabled = !isLoading
                    ) {
                        Text(
                            text = "立即注册",
                            color = MaterialTheme.colorScheme.primary,
                            fontWeight = FontWeight.Bold,
                            fontSize = 14.sp
                        )
                    }
                }
            }
        }
    }
}

// Login 函数保持不变
fun Login(
    user: String,
    pwd: String,
    onSuccess: (UserState.User) -> Unit,
    onError: (String) -> Unit
) {
    // 保持原有实现不变
    val client = OkHttpClient.Builder()
        .connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
        .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
        .writeTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
        .build()

    val jsonObject = JSONObject()
    jsonObject.put("username", user)
    jsonObject.put("password", pwd)
    val json = jsonObject.toString()

    val mediaType = "application/json; charset=utf-8".toMediaType()
    val requestBody = json.toRequestBody(mediaType)
    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user/signIn")
        .post(requestBody)
        .build()

    CoroutineScope(Dispatchers.IO).launch {
        try {
            Log.d("Login", "开始登录请求: username=$user")
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string()
            Log.d("Login", "收到响应: code=${response.code}, body=$responseBody")

            if (response.isSuccessful && responseBody != null) {
                val responseJson = JSONObject(responseBody)
                val success = responseJson.getBoolean("success")
                Log.d("Login", "解析响应成功: success=$success")
                withContext(Dispatchers.Main) {
                    if (success) {
                        val userJson = responseJson.optJSONObject("user")
                        if (userJson != null) {
                            val userId = userJson.getLong("id")
                            val username = userJson.getString("username")
                            val user = UserState.User(id = userId, username = username)
                            Log.d("Login", "登录成功: userId=$userId, username=$username")
                            onSuccess(user)
                        } else {
                            Log.e("Login", "用户信息为空")
                            onError("登录成功但获取用户信息失败")
                        }
                    } else {
                        val message = responseJson.optString("message", "登录失败")
                        Log.e("Login", "登录失败: $message")
                        onError(message)
                    }
                }
            } else {
                Log.e("Login", "网络请求失败: code=${response.code}")
                withContext(Dispatchers.Main) {
                    onError("网络请求失败: ${response.code}")
                }
            }
        } catch (e: Exception) {
            Log.e("Login", "登录异常", e)
            withContext(Dispatchers.Main) {
                onError("登录异常: ${e.message}")
            }
        }
    }
}

/**
 * 登录成功后初始化用户头像
 */
private fun initializeUserAvatarAfterLogin(userId: Long) {
    Log.d("LoginScreen", "🔥 登录成功后初始化用户头像，用户ID: $userId")
    CoroutineScope(Dispatchers.IO).launch {
        try {
            // 获取用户资料信息
            val profile = fetchUserProfileAfterLogin(userId)
            profile?.let {
                Log.d("LoginScreen", "🔥 获取到用户头像: ${it.avatar}")
                // 更新全局头像状态
                UserState.updateUserAvatar(it.avatar)
            }
        } catch (e: Exception) {
            Log.e("LoginScreen", "🔥 获取用户头像失败: ${e.message}")
        }
    }
}

/**
 * 获取用户资料信息
 */
private suspend fun fetchUserProfileAfterLogin(userId: Long): Profile? {
    return try {
        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url("${NetworkConfig.BASE_URL}/api/user-profile/$userId")
            .build()
        
        withContext(Dispatchers.IO) {
            try {
                val response = client.newCall(request).execute()
                val body = response.body?.string() ?: return@withContext null
                val json = Gson().fromJson(body, JsonObject::class.java)
                if (json.get("success")?.asBoolean == true) {
                    val data = json.getAsJsonObject("data")
                    Profile(
                        userId = data.get("userId")?.asLong ?: userId,
                        name = data.get("name")?.asString ?: "用户",
                        des = data.get("des")?.asString ?: "",
                        avatar = data.get("avatar")?.asString, // 头像URL
                        gender = data.get("gender")?.asString ?: "保密",
                        height = data.get("height")?.asDouble ?: 0.0,
                        weight = data.get("weight")?.asDouble ?: 0.0,
                        birthday = data.get("birthday")?.asString ?: "1990-01-01",
                        location = data.get("location")?.asString ?: ""
                    )
                } else {
                    null
                }
            } catch (e: Exception) {
                Log.e("LoginScreen", "网络请求失败: ${e.message}")
                null
            }
        }
    } catch (e: Exception) {
        Log.e("LoginScreen", "获取用户资料失败: ${e.message}")
        null
    }
}